package io.wdb.wxapp.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;

import io.wdb.wxapp.util.PayCommonUtil;
import io.wdb.wxapp.util.WxAppPayUtil;

@RestController
@RequestMapping("wxpay")
public class WxAppPaymentController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(WxAppPaymentController.class);
	/** 统一支付订单
	 * @param openid
	 * @return
	 */
	@RequestMapping(value = "payment", method = RequestMethod.POST)
	@ResponseBody
   public Object payment(HttpServletRequest request) {
		String openid = request.getParameter("openid");
		String totalFee = request.getParameter("chargeamount");
		logger.info("openid：{},创建支付{}",openid,totalFee);
       if (StringUtils.isEmpty(openid)) {
           return "empty openid";
       }
       Map<String, Object> result = new HashMap<>();
       try {

       	String timeStamp = PayCommonUtil.createTimestamp();
   		String nonceStr = PayCommonUtil.createNonceStr();
   		
   		String orderNo = System.currentTimeMillis()+"";
   		result.put("appid", appid);
   		result.put("timestamp", timeStamp);
   		result.put("nonceStr", nonceStr);
       	result.put("openid", openid);
       	result.put("orderNo", orderNo);
       	String prepayId = WxAppPayUtil.unifiedorder("微信小程序押金测试", orderNo, openid, totalFee,
       			appid, merchantId, notifyUrl, merchantKey);
       	//TODO 调起统一支付接口
       	logger.info("openid:{},统一下单返回:{}",openid,prepayId);
       	

   		SortedMap<Object, Object> signParams = new TreeMap<Object, Object>();
   		signParams.put("appId", appid);
   		signParams.put("nonceStr", nonceStr);
   		signParams.put("package", "prepay_id=" + prepayId);
   		signParams.put("timeStamp", timeStamp);
   		signParams.put("signType", "MD5");

   		// 生成支付签名，要采用URLENCODER的原始值进行SHA1算法！
   		String sign = PayCommonUtil.createSign(signParams, merchantKey);
       	
   		result.put("paySign", sign);
   		result.put("packageValue", "prepay_id=" + prepayId);
       	
       	return result;
       } catch (Exception e) {
       	
           logger.error(e.getMessage(), e);
           return e.toString();
       }
   }
	
}
